package com.purchasing.system.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.purchasing.system.model.Role;
import com.purchasing.system.repository.RoleRepository;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/roles")
public class RoleController {

    @Autowired
    private RoleRepository roleRepository;

    // 获取所有角色
    @GetMapping
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<List<Role>> getAllRoles() {
        List<Role> roles = roleRepository.findAll();
        return ResponseEntity.ok(roles);
    }

    // 创建新角色
    @PostMapping
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<Role> createRole(@RequestBody Role role) {
        try {
            Role savedRole = roleRepository.save(role);
            return new ResponseEntity<>(savedRole, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 根据ID获取角色
    @GetMapping("/{id}")
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<Role> getRoleById(@PathVariable Long id) {
        Optional<Role> roleData = roleRepository.findById(id);

        return roleData.map(role -> new ResponseEntity<>(role, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    // 更新角色
    @PutMapping("/{id}")
    public ResponseEntity<Role> updateRole(@PathVariable Long id, @RequestBody Role updatedRole) {
        Optional<Role> roleOptional = roleRepository.findById(id);

        if (roleOptional.isPresent()) {
            Role existingRole = roleOptional.get();

            // 更新角色名称
            if (updatedRole.getName() != null) {
                existingRole.setName(updatedRole.getName());
            }

            // 更新权限集合
            if (updatedRole.getPermissions() != null) {
                // 先清除现有权限
                existingRole.getPermissions().clear();
                // 添加新权限
                existingRole.getPermissions().addAll(updatedRole.getPermissions());
            }

            return new ResponseEntity<>(roleRepository.save(existingRole), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    // 删除角色
    @DeleteMapping("/{id}")
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<HttpStatus> deleteRole(@PathVariable Long id) {
        try {
            roleRepository.deleteById(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 删除所有角色
    @DeleteMapping
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<HttpStatus> deleteAllRoles() {
        try {
            roleRepository.deleteAll();
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}